package peer.p2pnet.message;

import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.UnknownHostException;

import peer.Message;
import peer.tools.ByteIntSwitch;
import peer.tools.ByteShortSwitch;

public class GetOutAddressMessage2 extends Message{
	public short sType=peer.tools.MessageType.sType_getOutAddressMessage2;
	InetAddress outIp;
	int outPort;
	byte[] dpData=new byte[12];
	public GetOutAddressMessage2(InetAddress outIp,int outPort){
		this.outIp=outIp;
		this.outPort=outPort;
		ByteShortSwitch.toByteArray(ver, dpData, 0);  //add: ver
		ByteShortSwitch.toByteArray(sType, dpData, 2);  //add: service type
		System.arraycopy(outIp.getAddress(), 0, dpData, 4, 4);  //add: outIp
		ByteIntSwitch.toByteArray(this.outPort, dpData, 8);  //add outPort
		dp=new DatagramPacket(dpData,dpData.length);
	}
	
	public GetOutAddressMessage2(DatagramPacket dp){
		this.dp=dp;
		dpData=dp.getData();
		ver=ByteShortSwitch.toShort(dpData, 0);
		sType=ByteShortSwitch.toShort(dpData, 2);
		byte[] data=new byte[4];
		System.arraycopy(dpData, 4, data, 0, 4);
		try {
			outIp=InetAddress.getByAddress(data);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		outPort=ByteIntSwitch.toInt(dpData, 8);
	}
	
	public InetAddress getOutIp(){
		return outIp;
	}
	
	public int getOutPort(){
		return outPort;
	}
}
